import axios from "axios";
import { Message } from "element-ui";
const instance = axios.create({
  baseURL: "/api",
  timeout: 900000,
  headers: { "Authori-zation": "Bearer " + localStorage.getItem("token") },
});
// 添加请求拦截器
instance.interceptors.request.use(
  function(config) {
    // 在发送请求之前做些什么
    config.headers = {
      "Authori-zation": "Bearer " + localStorage.getItem("token"),
    };
    return config;
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  function(response) {
    // 对响应数据做点什么
    // if (response.data.status == 200) {
    //   //成功提示
    //   Message({ type: "success", message: response.data.msg });
    // }
    return response;
  },
  function(error) {
    // 对响应错误做点什么
    console.log(error);
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          Message({ type: "error", message: "错误请求" });

          break;

        case 401:
          Message({ type: "error", message: "未授权，请重新登录" });
          sessionStorage.setItem("toPath", window.location.pathname);
          localStorage.removeItem("token");
          window.location.href = "/login";
          break;
        case 410000:
          Message({ type: "error", message: "未授权，请重新登录" });
          sessionStorage.setItem("toPath", window.location.pathname);
          localStorage.removeItem("token");
          window.location.href = "/login";
          break;

        case 403:
          Message({ type: "error", message: "拒绝访问" });

          break;

        case 404:
          Message({ type: "error", message: "未找到该资源" });
          // sessionStorage.setItem("toPath", window.location.pathname);
          // localStorage.removeItem("token");
          // window.location.href = "/login";
          break;

        case 405:
          error.message = "请求方法未允许";
          Message({ type: "error", message: "请求方法未允许" });

          break;

        case 408:
          Message({ type: "error", message: "请求超时" });

          break;

        case 500:
          Message({ type: "error", message: "服务器端出错" });
          break;

        case 501:
          Message({ type: "error", message: "网络未实现" });
          break;

        case 502:
          Message({ type: "error", message: "网络错误" });

          break;

        case 503:
          Message({ type: "error", message: "服务不可用" });

          break;

        case 504:
          Message({ type: "error", message: "网络超时" });
          break;

        case 505:
          Message({ type: "error", message: "http版本不支持该请求" });

          break;

        default:
          Message(`'连接错误'${error.response.status}`);
      }
    } else {
      Message("连接到服务器失败");
    }
    return Promise.reject(error);
  }
);

export default instance;
